<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 회원정보 수정 컨트롤러
 */
class Change extends CI_Controller {
	
	var $data = array();
	
	function __construct() {
		parent::__construct();
		$this->data['sess_userinfo'] = $this->session->userdata('userinfo');

		$this->load->model('mypage/Change_model', 'change', TRUE);
	}

	// Default
	function index() {
		log_message('debug', "@@@@ Change::index()");

	}
	
	/**
	 * 패스워드 변경 폼
	 */
	function password() {
		log_message('debug', "@@@@ Change::password()");
		
		$this->load->view('mypage/change_password_v', $this->data);
	}

	/**
	 * 패스워드 변경 완료
	 */
	function password_ok() {
		log_message('debug', "@@@@ Change::password_ok()");
		
		$current_pwd = $this->input->post('current_pwd', TRUE);
		$new_pwd     = $this->input->post('pwd', TRUE);

		$current_pwd = crypt($current_pwd, $this->config->item('encryption_key'));	//패스워드는 암호화해서 비교
		$new_pwd     = crypt($new_pwd, $this->config->item('encryption_key'));
		
		// 이전과 동일한 패스워드인지 체크
		if ($current_pwd == $new_pwd) {
			echo "<script type='text/javascript'>";
			echo "	alert('새 비밀번호가 현재의 비밀번호와 같습니다.');";
			echo "	history.back();";
			echo "</script>";
			return;
		}
		
		// 현재 패스워드 일치 체크
		$is_valid = $this->change->check_password($this->data['sess_userinfo']['user_id'],$current_pwd);
		if ($is_valid == FALSE) {
			echo "<script type='text/javascript'>";
			echo "	alert('현재의 비밀번호가 일치하지 않습니다.');";
			echo "	history.back();";
			echo "</script>";
			return;
		}
		
		// 새 패스워드로 변경		
		$this->change->update_member_password($this->data['sess_userinfo']['user_id'],$new_pwd);

		echo "<script type='text/javascript'>";
		echo "	alert('비밀번호 변경이 완료되었습니다.');";
		echo "	location.href = '/mypage/mypage';";
		echo "</script>";
	}
	
	/**
	 * 패스워드 확인 폼
	 */
	function pwd_check() {
		log_message('debug', "@@@@ Change::pwd_check()");
		
		$this->load->view('mypage/pwd_check_v', $this->data);
	}

	/**
	 * 패스워드 확인 완료
	 */
	function pwd_check_ok() {
		log_message('debug', "@@@@ Change::pwd_check_ok()");

		$pwd = $this->input->post('pwd', TRUE);
		$pwd = crypt($pwd, $this->config->item('encryption_key'));	//패스워드는 암호화해서 비교
		
		// 현재 패스워드 일치 체크
		$is_valid = $this->change->check_password($this->data['sess_userinfo']['user_id'],$pwd);
		if ($is_valid == FALSE) {
			echo "<script type='text/javascript'>";
			echo "	alert('비밀번호가 일치하지 않습니다.');";
			echo "	history.back();";
			echo "</script>";
			return;
		}

		// 패스워드 확인 세션 생성
		$this->session->set_userdata('pwd_ok','Y');
		
		// 가려던 페이지로 이동
		$return_url = $this->input->get('return_url', TRUE);
		redirect($return_url);
	}

	/**
	 * 회원정보 수정 폼
	 */
	function info() {
		log_message('debug', "@@@@ Change::info()");
		
		// 패스워드 확인을 거치지 않았으면
		$pwd_ok =  $this->session->userdata('pwd_ok');
		if (empty($pwd_ok) || $pwd_ok != 'Y') {
			redirect('/mypage/change/pwd_check?return_url=/mypage/change/info');
			return ;
		}
		
		// 패스워드 확인 세션 제거
		$this->session->unset_userdata('pwd_ok');
		
		// 회원정보
		$this->data['member']      = $this->change->get_member($this->data['sess_userinfo']['user_id']);
		
		// 회원사진
		$member_file = $this->change->get_member_file($this->data['member']['idx']);
		if (!empty($member_file)) {
			$this->data['member_img_url'] = $member_file['file_url'].$member_file['raw_name'].'_89'.$member_file['file_ext'];
		} else {
			$this->data['member_img_url'] = '/images/common/user_img.png';
		}

		$this->data['member']['birth_yyyy'] = substr($this->data['member']['birthdate'], 0,4);
		$this->data['member']['birth_mm']   = substr($this->data['member']['birthdate'], 5,2);
		$this->data['member']['birth_dd']   = substr($this->data['member']['birthdate'], 8,2);

		$cellphone = explode('-', $this->data['member']['cellphone']);
		$this->data['member']['cell_1'] = $cellphone[0];
		$this->data['member']['cell_2'] = $cellphone[1];
		$this->data['member']['cell_3'] = $cellphone[2];
		
		$this->load->view('mypage/change_info_v', $this->data);
	}
	
	/**
	 * 닉네임 중복체크 (AJAX)
	 */
	function nickname_check() {
		log_message('debug', "@@@@ Change::nickname_check()");

		// 폼 정보 가져오기
		$nickname = $this->input->post('nickname', TRUE);

		// 금칙어
		if (preg_match('/(운영자|관리자|개발자)/',$nickname) > 0) {
			echo 'false';
			exit;
		}
		
		$is_alreay = $this->change->is_already_nickname($this->data['sess_userinfo']['user_id'], $nickname);
		if ($is_alreay == TRUE) {
			echo 'false';
		} else {
			echo 'true';
		}
		exit;
	}
	
	/**
	 * 이메일 중복체크 (AJAX)
	 */
	function email_check() {
		log_message('debug', "@@@@ Change::email_check()");

		// 폼 정보 가져오기
		$email = $this->input->post('email', TRUE);
		
		$is_alreay = $this->change->is_already_email($this->data['sess_userinfo']['user_id'], $email);
		if ($is_alreay == TRUE) {
			echo 'false';
		} else {
			echo 'true';
		}
		exit;
	}

	/**
	 * 회원정보 수정 완료
	 */
	function info_ok() {
		log_message('debug', "@@@@ Change::info_ok()");
		
		// 파일 저장 
		$result_upload = $this->_do_upload();
		
		// 파일이 있는데 업로드 에러일경우 
		if (!is_array($result_upload)) {
			log_message('error','@@ _do_upload error return='.$result_upload);

			if ($result_upload == 'FAIL_MAXIMUM_SIZE') {
				echo "<script type='text/javascript'>";
				echo "	alert('회원 사진의 해상도가 큽니다.');";
				echo "	history.back();";
				echo "</script>";
				return;
			}
			elseif ($result_upload == 'FAIL_LARGE_FILE') {
				echo "<script type='text/javascript'>";
				echo "	alert('회원 사진의 파일사이즈가 큽니다.');";
				echo "	history.back();";
				echo "</script>";
				return;
			}
			elseif($result_upload != 'FAIL_NOT_SELECT') {
				echo "<script type='text/javascript'>";
				echo "	alert('회원 사진 등록 실패');";
				echo "	history.back();";
				echo "</script>";
				return;
			}
		} else {
			// 썸네일 이미지 생성
			$this->load->library('image_lib'); 
			$this->_create_thumb($result_upload, 36, 36);
			$this->_create_thumb($result_upload, 50, 50);
			$this->_create_thumb($result_upload, 60, 60);
			$this->_create_thumb($result_upload, 89, 89);
			
			// 회원사진을 처음 등록하는거면 보너스 포인트를 준다.
			$tmp_member = $this->change->is_already_member_file($this->data['sess_userinfo']['user_id']);
			if ($tmp_member == FALSE) {
				$this->load->model('point/Point_model', 'point_model', TRUE);
				$this->point_model->update_activity_point($this->data['sess_userinfo']['user_id'], 'REG_PHOTO');
			}
		}
		
		$member['idx']           = $this->input->post('idx', TRUE);
		$member['nickname']      = $this->input->post('nickname', TRUE);
		$member['sex']           = $this->input->post('sex', TRUE);
		$member['email']         = $this->input->post('email', TRUE);
		$member['mailing_yn']    = $this->input->post('mailing_yn', TRUE);
		$member['mailing_yn']    = $member['mailing_yn'] != 'Y' ? 'N' : 'Y';
		$member['sms_yn']        = $this->input->post('sms_yn', TRUE);
		$member['sms_yn']        = $member['sms_yn'] != 'Y' ? 'N' : 'Y';
		$member['birthdate']     = $this->input->post('birthdate', TRUE);
		$member['birthtime']     = $this->input->post('birth_hh', TRUE);
		$tmp_birth_solunar       = $this->input->post('birth_solunar', TRUE);
		$tmp_birth_solunar       = preg_split("/_/", $tmp_birth_solunar);
		$member['birth_solunar'] = $tmp_birth_solunar[0];
		$member['cl_year']       = $tmp_birth_solunar[1];
		$member['cellphone']     = $this->input->post('cellphone', TRUE);
		$member['zip_code']      = $this->input->post('zip_code', TRUE);
		$member['addr1']         = $this->input->post('addr1', TRUE);
		$member['addr2']         = $this->input->post('addr2', TRUE);

		// DB에 회원 등록
		$this->change->update_member($this->data['sess_userinfo']['user_id'], $member, $result_upload);


		// 사진 업로드 보너스 포인트 지급
		//$this->load->model('point/Point_model', 'point_model', TRUE);
		//$this->point_model->update_activity_point($member['user_id'], 'JOIN');
		
		// 세션 정보를 갱신한다.
		$arr_userinfo = $this->session->userdata('userinfo');
		$arr_userinfo['nickname'] = $member['nickname'];
		$this->session->set_userdata('userinfo', $arr_userinfo);
	

		echo "<script type='text/javascript'>";
		echo "	alert('회원 정보 수정이 완료되었습니다.');";
		echo "	location.href = '/mypage/mypage';";
		echo "</script>";
	}

	/**
	 * 파일 업로드
	 */
	function _do_upload() {
		log_message('debug', "@@@@ Change::_do_upload()");
		
		$target_dir = date('Ym',time());
		log_message('debug','@@ target_dir='.$target_dir);
		
		$config['upload_path']   = "/home/tonnet/unsin/unsin2012/uploads/member_face/$target_dir/";
		$config['allowed_types'] = 'gif|jpg';
		$config['max_filename']  = '255';
		$config['max_size']      = '1024';
		$config['max_width']     = '1920';
		$config['max_height']    = '1080';
		$config['encrypt_name']  = TRUE;
		$config['remove_spaces'] = TRUE;
		
		$this->load->library('upload', $config);
		
		if ( ! $this->upload->do_upload()) {
			$result = $this->upload->display_errors();
			log_message('error','@@ _do_upload error='.$result);
			log_message('error','@@ _do_upload error_msg='.print_r($this->upload->error_msg,TRUE));
			if ($this->upload->error_msg[0] == 'The image you are attempting to upload exceedes the maximum height or width.') {
				return 'FAIL_MAXIMUM_SIZE';
			} elseif ($this->upload->error_msg[0] == 'The file you are attempting to upload is larger than the permitted size.') {
				return 'FAIL_LARGE_FILE';
			} elseif ($this->upload->error_msg[0] == 'You did not select a file to upload.') {
				return 'FAIL_NOT_SELECT';
			}
			return 'FAIL';
		}
		
		$result = $this->upload->data();
		log_message('debug','@@ _do_upload data='.print_r($result,TRUE));
		
		return $result;
	}
	
	/**
	 * 섬네일 이미지 만들기
	 */
	function _create_thumb($result_upload, $width, $height) {
		log_message('debug', "@@@@ Change::create_thumb($result_upload, $width, $height)");
		
		$config['image_library']  = 'gd2';
		$config['source_image']   = $result_upload['file_path'].$result_upload['file_name'];
		$config['new_image']      = $result_upload['file_path'].$result_upload['raw_name']."_$width".$result_upload['file_ext'];
		$config['create_thumb']   = TRUE;
		$config['thumb_marker']   = FALSE;
		$config['maintain_ratio'] = TRUE;	// 가로세로 비율 유지
		$config['master_dim']     = 'auto';	// 크기 조절시 큰 축을 기준
		$config['width']	      = $width;
		$config['height']         = $height;

		$this->image_lib->clear();
		$this->image_lib->initialize($config);
		$this->image_lib->resize();
	}
	
	/**
	 * 탈퇴 폼
	 */
	function dropout() {
		log_message('debug', "@@@@ Change::dropout()");
		
		$this->load->view('mypage/dropout_v', $this->data);
	}
	
	/**
	 * 회원탈퇴 확인 창
	 */
	function dropout_confirm() {
		log_message('debug', "@@@@ Change::dropout_confirm()");

		// 패스워드 확인을 거치지 않았으면
		$pwd_ok =  $this->session->userdata('pwd_ok');
		if (empty($pwd_ok) || $pwd_ok != 'Y') {
			redirect('/mypage/change/pwd_check?return_url=/mypage/change/dropout_confirm');
			return ;
		}
		
		// 패스워드 확인 세션 제거
		$this->session->unset_userdata('pwd_ok');

		echo "<script src='/js/utility/common_util.js' type='text/javascript'></script>";
		echo "<script type='text/javascript'>";
		echo "	openPopup('/mypage/change/dropout_confirm_ok', 530,280);";
		echo "	history.go(-2);";
		echo "</script>";
	}
	
	function dropout_confirm_ok() {
		$this->load->view('mypage/dropout_confirm_pop_v', $this->data);
	}

	/**
	 * 탈퇴 완료
	 */
	function dropout_ok() {
		log_message('debug', "@@@@ Change::dropout_ok()");
		
		$member = $this->change->get_member($this->data['sess_userinfo']['user_id']);

		// 탈퇴 완료 메일 발송
		$this->_send_email_dropout($member['email'], $member['user_name']);
		
		// 탈퇴상태로 변경		
		$this->change->update_member_dropout($this->data['sess_userinfo']['user_id']);
		
		echo "<script type='text/javascript'>";
		echo "	alert('탈퇴신청이 완료되었습니다.');";
		echo "	opener.location.href = '/member/login/logout';";
		echo "	window.close();";
		echo "</script>";
	}
	
	/**
	 * 탈퇴 완료 메일발송
	 */
	function _send_email_dropout($to_email, $user_name) {
		log_message('debug',"@@@@ Change::_send_email_dropout($to_email, $user_name)");
		
		$params['to_email']  = $to_email;
		$params['user_name'] = $user_name;

		$url = ROOT_URL."/external/xpm4/mail-dm_out.php";
		$req = new HttpRequest($url, HttpRequest::METH_POST);
		$req->addPostFields($params);

		try {
			$return_obj = $req->send()->getBody();
			$this->logsql->log_result($return_obj);
			return TRUE;
		} catch (HttpException $ex) {
			log_message('error','@@ 탈퇴 완료 메일 발송중 에러 발생');
			echo $ex;
			return FALSE;
		}
	}

}

/* End of file change.php */
/* Location: ./application/controllers/mypage/change.php */